<?php
class Thamza_Controller_Plugin_CheckHasAccess extends Zend_Controller_Plugin_Abstract {

	/**
	 * Checks if a user is allowed to access the current controller
	 * Returns true if allowed
	 * redirects to the noaccess.phtml found in auth controller if user is not allowed
	 *
	 * @param Zend_Controller_Request_Abstract $request
	 * @return unknown
	 */
	public function preDispatch(Zend_Controller_Request_Abstract $request) {
		try {
            
			$moduleName         = $this->getRequest()->getModuleName();
			$controllerName     = $this->getRequest()->getControllerName();
			$actionName         = $this->getRequest()->getActionName();
			$frontController    = Zend_Controller_Front::getInstance();
			$user = Zend_Auth::getInstance()->getIdentity();

//			if($controllerName == 'staff' AND !isset($user)) {
//				throw new Exception('You must login to access this page.');
//			}

			//check $user->mygroups['group_permission'] array
		    //echo $moduleName.' '.$controllerName.' '.$actionName;
			//Zend_Debug::dump($user->mygroups['group_permission']);

			if (isset($user)) {
				$permissions = $user->mygroups['group_permission'];

				//check for module ONLY - controller and action must be NULL
				for($i=0;$i<count ($permissions);$i++) {
					if ($permissions[$i]['module_name'] == $moduleName AND
					$permissions[$i]['controller_name'] == NULL AND
					$permissions[$i]['action_name'] == NULL AND
					$permissions[$i]['permission'] == 'deny') {
						throw new Exception('You are not allowed to access this module.');
					}
				}

				//check for controller+module - action is blank
				for($i=0;$i<count($permissions);$i++) {
					if ($permissions[$i]['module_name'] == $moduleName AND
					$permissions[$i]['controller_name'] == $controllerName AND
					$permissions[$i]['action_name'] == NULL AND
					$permissions[$i]['permission'] == 'deny') {
						throw new Exception('You are not allowed to access this controller.');
					}
				}
                
				//check for the module / controller / action - look for deny
				for($i=0;$i<count($permissions);$i++) {
					//echo $permissions[$i]['module_name'].' '.$permissions[$i]['permission'].'<br>';
					if ($permissions[$i]['module_name'] == $moduleName AND
					$permissions[$i]['controller_name'] == $controllerName AND
					$permissions[$i]['action_name'] == $actionName AND
					$permissions[$i]['permission'] == 'deny') {
						throw new Exception('You are not allowed to access this page.');
					}
				}
				
				//if guest session exists, unset it
				Zend_Session::sessionExists('Admin_Session')?Zend_Session::namespaceUnset('Admin_Session'):'';

			} elseif(Zend_Session::namespaceIsset('Admin_Session')) {
				//this part executes only when the Admin_Session is set
				//so that we only have to query the database once
				//querying the database is in the else
				//after querying, the Admin_Session is set.

				$guest = new Zend_Session_Namespace('Admin_Session');

				$permissions = $guest->guestRoles;
				//Zend_Debug::dump($guest);
				//echo 'guest session exists!';
				//check for module ONLY - controller and action must be NULL
				for($i=0; $i<count($permissions); $i++) {
					if ($permissions[$i]['module_name'] == $moduleName AND
					$permissions[$i]['controller_name'] == NULL AND
					$permissions[$i]['action_name'] == NULL AND
					$permissions[$i]['permission'] == 'deny') {
						throw new Exception('You are not allowed to access this module.');
					}
				}

				//check for controller+module - action is blank
				for($i=0;$i<count($permissions);$i++) {
					if ($permissions[$i]['module_name'] == $moduleName AND
					$permissions[$i]['controller_name'] == $controllerName AND
					$permissions[$i]['action_name'] == NULL AND
					$permissions[$i]['permission'] == 'deny') {
						throw new Exception('You are not allowed to access this controller.');
					}
				}

				//check for the module / controller / action - look for deny
				for($i=0;$i<count($permissions);$i++) {
					//echo $permissions[$i]['module_name'].' '.$permissions[$i]['permission'].'<br>';
					if ($permissions[$i]['module_name'] == $moduleName AND
					$permissions[$i]['controller_name'] == $controllerName AND
					$permissions[$i]['action_name'] == $actionName AND
					$permissions[$i]['permission'] == 'deny') {
						throw new Exception('You are not allowed to access this page.');
					}
				}
			} else {
				//query the database for permissions and then set Admin_Session
				$guestSession = new Zend_Session_Namespace('Admin_Session');

				//Not logged in, so check guest/unregistered user
				//query permissions table
				$base = new Cpanel_Model_DbTable_BasicModel();
				$dbAdapter = $base->getAdapter();
				$sql = '
                    SELECT *
                    FROM permissions
                    WHERE group_name="admin"
                ';
				$permissions = $dbAdapter->fetchAll($sql);

				//set this to session, so that we will not be querying the db for every guest that is logged in.
				$guestSession->guestRoles = $permissions;

				//check for module ONLY - controller and action must be NULL
				for($i=0;$i<count($permissions);$i++) {
					if ($permissions[$i]['module_name'] == $moduleName AND
					$permissions[$i]['controller_name'] == NULL AND
					$permissions[$i]['action_name'] == NULL AND
					$permissions[$i]['permission'] == 'deny') {
						throw new Exception('You are not allowed to access this module.');
					}
				}

				//check for controller+module - action is blank
				for($i=0;$i<count($permissions);$i++) {
					if ($permissions[$i]['module_name'] == $moduleName AND
					$permissions[$i]['controller_name'] == $controllerName AND
					$permissions[$i]['action_name'] == NULL AND
					$permissions[$i]['permission'] == 'deny') {
						throw new Exception('You are not allowed to access this controller.');
					}
				}

				//check for the module / controller / action - look for deny
				for($i=0;$i<count($permissions);$i++) {
					//echo $permissions[$i]['module_name'].' '.$permissions[$i]['permission'].'<br>';
					if ($permissions[$i]['module_name'] == $moduleName AND
					$permissions[$i]['controller_name'] == $controllerName AND
					$permissions[$i]['action_name'] == $actionName AND
					$permissions[$i]['permission'] == 'deny') {

						throw new Exception('You are not allowed to access this page.');
					}
				}
			}
			return true;

		} catch (Exception $e) {
			$this->getResponse()->setHttpResponseCode(403);
			
			// Repoint the request to the default error handler
			$request->setModuleName('cpanel');
			$request->setControllerName('error');
			$request->setActionName('noaccess');
            
            // Set up the error handler
            $error = new Zend_Controller_Plugin_ErrorHandler();
            $error->type = Zend_Controller_Plugin_ErrorHandler::EXCEPTION_OTHER;
            $error->request = clone($request);
            $error->exception = $e;
            $request->setParam('error_handler', $error);
		}
	}
}
?>